package com.emailsystem.emailsystem.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emailsystem.emailsystem.common.ApiRestResponse;
import com.emailsystem.emailsystem.domain.Connection;
import com.emailsystem.emailsystem.domain.User;
import com.emailsystem.emailsystem.exception.MailExceptionEnum;
import com.emailsystem.emailsystem.service.ClientService;
import com.emailsystem.emailsystem.service.UserService;
import com.emailsystem.emailsystem.service.impl.POP3Impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ClientService clientService;


    @PostMapping("/defaultLogin")
    public ApiRestResponse login(@RequestBody User user2) throws IOException {
        String account = user2.getAccount();
        String password = user2.getPassword();
        userService.setCurrentUser(account);

        //对账号合法性进行判断
        String emailRegex="^[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([.-][A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern pattern = Pattern.compile(emailRegex);
        Matcher matcher = pattern.matcher(account);
        if(!matcher.matches()) {
            return ApiRestResponse.error(MailExceptionEnum.ILLEGAL_ACCOUNT);
        }
//        有账号密码,和数据库对一下子就行
        User user1 = userService.getUserByAccount(account);
        if (null!=user1) {
            String password1 = user1.getPassword();
            if(password1.equals(password)){
                //登录通过
                JSONObject obj=new JSONObject();
                obj.put("nickname",user1.getNickname());
                obj.put("account",account);
                return ApiRestResponse.success(obj);
            }else{
                //密码错误
                return ApiRestResponse.error(MailExceptionEnum.WRONG_PASSWORD);
            }
        }else{
//        无账号密码，pop3请求出战
            String connectionMsg = clientService.connect(account, password);
            if(connectionMsg.equals("登陆成功")){
                //插入到数据库
                userService.insert(account,password);
                JSONObject obj=new JSONObject();
                obj.put("account",account);
                obj.put("nickname",null);
                return ApiRestResponse.success(obj);
            }else if(connectionMsg.equals("账号错误")){
                return ApiRestResponse.error(MailExceptionEnum.NOT_EXIST_ACCOUNT);
            }else if(connectionMsg.equals("密码错误")){
                return ApiRestResponse.error(MailExceptionEnum.WRONG_PASSWORD);
            }else{
                return ApiRestResponse.error(MailExceptionEnum.WRONG_SERVER);
            }
        }
    }

    @PostMapping("/updateLogin")
    public ApiRestResponse login2(@RequestBody User user) throws IOException {
        String account = user.getAccount();
        String password = user.getPassword();
        //对账号合法性进行判断
        String emailRegex="^[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([.-][A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern pattern = Pattern.compile(emailRegex);
        Matcher matcher = pattern.matcher(account);
        if(!matcher.matches()) {
            return ApiRestResponse.error(MailExceptionEnum.ILLEGAL_ACCOUNT);
        }
        String connectionMsg = clientService.connect(account, password);
            if(connectionMsg.equals("登陆成功")){
                //更新到数据库
                userService.update(account,password);
                User user1 = userService.getUserByAccount(account);
                JSONObject obj=new JSONObject();
                obj.put("account",account);
                obj.put("nickname",user1.getNickname());
                return ApiRestResponse.success(obj);
            }else if(connectionMsg.equals("账号错误")){
                return ApiRestResponse.error(MailExceptionEnum.NOT_EXIST_ACCOUNT);
            }else if(connectionMsg.equals("密码错误")){
                return ApiRestResponse.error(MailExceptionEnum.WRONG_PASSWORD);
            }else{
                return ApiRestResponse.error(MailExceptionEnum.WRONG_SERVER);
            }
    }

    @PostMapping("/getConnection")
    public ApiRestResponse getConnection(@RequestBody User user){
        String account = user.getAccount();
        ArrayList<Connection> connections= userService.getConnection(account);
        JSONArray jsonArray = new JSONArray();
        for (Connection connection: connections) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("connection",connection);
            jsonArray.add(jsonObject);
        }
       return ApiRestResponse.success(jsonArray);
    }
    /**
     * 修改端口和协议
     * @param connection
     * @return
     */
    @PostMapping("/updateConnection")
    public ApiRestResponse setConnection(@RequestBody Connection connection){
        String account = connection.getAccount();
        String serverIP = connection.getIP();
        Integer port = connection.getPort();
        String protocol = connection.getProtocol();
        userService.updateConnection(account,serverIP,port,protocol);
        return ApiRestResponse.success();
    }

    @GetMapping("/getCurrentUser")
    public ApiRestResponse getCurrentUser(){
        JSONObject res=new JSONObject();
        if(userService.getCurrentUser()!=null) {
            if (userService.getCurrentUser().getAccount() != null) {
                res.put("CurrentUser", userService.getCurrentUser().getAccount());
            }
            return ApiRestResponse.success(res);
        }else{
           return ApiRestResponse.error(MailExceptionEnum.NEED_LOGIN);
        }

    }

    @PostMapping("/addConnection")
    public ApiRestResponse addConnection(@RequestBody Connection connection){
        String account = connection.getAccount();
        String serverIP = connection.getIP();
        Integer port = connection.getPort();
        String protocol = connection.getProtocol();
        userService.addConnection(account,serverIP,port,protocol);
        return ApiRestResponse.success();
    }

    //旧
    /**
     //     * 用户登录，post请求发送一个对象过来，只需要看账号密码
     //     * @param user
     //     * @return
     //     */
//    @PostMapping("/login")
//    public ApiRestResponse login(@RequestBody User user){
//        User u=userService.getUserByAccountAndPassword(user.getAccount(), user.getPassword());
//        boolean flag;
//        JSONObject obj=new JSONObject();
//        if(null==u)flag=false;
//        else {
//            flag=true;
//            obj.put("nickname",u.getNickname());
//        }
//        //这个地方登录成功后，还应该返回用户的昵称以便于前端展示用户的昵称
//        if(flag) return ApiRestResponse.success(obj);
//        else return ApiRestResponse.error(MailExceptionEnum.LOGIN_ERR);
//    }
//
//    @PostMapping("/register")
//    public ApiRestResponse register(@RequestBody User user){
//        //账号是否合理,也就是说这个账号不是邮箱账号
//        String account=user.getAccount();
//        String emailRegex="^[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([.-][A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
//        Pattern pattern = Pattern.compile(emailRegex);
//        Matcher matcher = pattern.matcher(account);
//        boolean isValidEmail = matcher.matches();
//
//        if(!isValidEmail) {
//            return ApiRestResponse.error(MailExceptionEnum.ACCOUNT_FORMAT_ERR);
//        }
//        //返回一个空的jsonobj 本来想返回null的，不知道前端是否能处理null 空obj没问题
//        JSONObject jsonObject = new JSONObject();
//        boolean isExistence=userService.testAccountExistence(account);
//        if(isExistence){
//            return ApiRestResponse.error(MailExceptionEnum.ACCOUNT_ALREADY_EXISTS);
//        }
//        //一般来说，insert就不用返回Boolean了，插入失败自然会报错
//        boolean flag = userService.insert(user.getNickname(), user.getAccount(), user.getPassword());
//        if(flag) return ApiRestResponse.success(jsonObject);
//        else return ApiRestResponse.error(MailExceptionEnum.REGISTER_ERR);
//    }



}
